package com.leetcode.August;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 138. 随机链表的复制
 * @Author: Mr.Fxy
 * @CreateTime: 2024-08-27 16:30
 */
public class LC138随机链表的复制 {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Node, Node> mp = new HashMap<>();
        Node current = head;
        while (current != null){
            Node new=new Node(current.val);
            mp.put(current,new);
            current=current.next;
        }
        // 复制next和random
        current=head;
        while (current!=null){
            Node new=mp.get(current);
            new.next=mp.get(current.next);
            new.random=mp.get(current.random);
            current=current.next;
        }
        // 返回新链表的头结点
        return mp.get(head);
    }
}
